_package("caf.core");

_import("alz.core.Plugin");

/**
 * CloudAPI 手机本地扩展
 */
_class("CloudApi", Plugin, function(){
	var androidPackageName = "com.aliyun.cloudapi.android.";
	var commonPackageName = "com.aliyun.cloudapi.common.";
	var personalPackageName = "com.aliyun.cloudapi.personal.";
	var _token = "xxxxxxxxxxxxxxx";
	var _sign = "hRJ2I5oyGUCkEZTPvMLjrl7H0wfxYAsu";
	var base64 = "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMEQwGF463kzcAAAcXSURBVFjDrZfbbxxXHcc/Z3Z2Zz12vL7seuPb2nHuF9omzkXExCVqC1SiKhIChERB8ICAN/gTeAEJBRBCQuINUUEjtWqREkMEiRopCYQkpLGx40vrOIkTX3a93svsjOd2Dg+bOr4kwS7Mw87s7k/n9znf3/l99RuhlFJs4rp9+zYjIyPs2bOHuro6urq6+F8usRkAzyrz81OnONy7l79cuMSuXbu5eu0mvb29FAoF+vv7kVJy+PBhTNP8PwOUFpk4+y6nBi7w2olPc3f6Acnde6m1swzmXA5uT3H+6hDd3d3cGrpNT08PUkp27dqFEIL+/n5SqdS6ZbUNJQ98wvFBMk0Jfvb11+nKZ/lMupnpPw/Q4ilGBgdptCVOvsju9g5OJON0dLSzPRFlbGyM82dP86tfnvrkCoSTo6g7YyhgxUe1LMUiM9MzRIXGzfkc0rJw4jXczBXo62rn+kKR7x05gN1cz2zlAS9++Uer1tb/W3JVWiScGAalUFKC/Dh59a7HYnT2dIGCV7s7cUslYvVb+NTfr9HYWMf04L+JH9xNULeV1tbU5hXwLp9H5uZA10GPgu+hPA9kuEKIRw9KrRFIgYILQ6O0vvF9FvOTvHz85Y0r4I8O4d+/g4ib4LpQsRFmLaK+AVmxUHYFgoDlPSi1Bghmslkma5N0JxrRFsJ1OZ4KoDwX99oVlOciXA+RaISohiwVUPmAS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wTooYBrqKAbDVX2RnbTOJRigHgqIwsENJDEA2Q1ABILl1B507DqwaWPWNTsSvnPs8F2cvAnC09QhSSDw8Mk3tfDX/TRiEo1t6+Q1glm9gAi0HvgAEQIWWvTt5/vYPmD8HxVQfmZcGME1z41Ox+K3gyhuXEEpjSS5xx7rD9NJ9FvwsEwvj5MNZ/jE8xHWg91s/ru5c2VAZAW+M0M/jFvOIqM3IJQvj+BCZTGbjCgDk/QVUKFhSDrPeLFPFKfLuPPP2HLlwZsUUOw+hA7ICwTSUh5AyQHoBmlYdSnK5HOl0euMAfak+vvjW6wAc7jzEoY4XKPsFPpgeYip3H4B9kX0saYIbb/4agJY922hvLyFRzDyE7KRfHXYi+zZ/BgZeGuDevXvkcjlOjp8k1dCM5ZeZyt3n7ea3qa2tJR6PI2IxXMDzPBg9SaqhjjCA7KTD1Iq4ZDKJYRgbBzBNk0wmQzqdhnFYlHPY2ADU1taybds2mpqaiEQi1SqEIffGAUNDi7IuzjAMTNPcOICu69TX1y+X4/Lw5WXZ4/E4TU1N61695lJ9DF+8vCz7k+LEZt+OAUql0nI5AJLJJJlMZhlwM3GfCCAIAmzbxnWrdrwsp65vOu4/HQLU72xlGzEAAAAASUVORK5CYII=";
	function stub(str){
		if(typeof runtime != "undefined"){
			runtime.log("[stub]" + str);
		}
	}
	var win = window;
	this.__debug__ = typeof win.JsCloudAPI == "undefined";  //通过该属性识别真实接口还是模拟接口
	/* 全局事件响应 */
	window.onPause = function(){
		console.log("[window.onPause]开始执行");
		//CloudAPI.Utility.toast("[window.onPause]开始执行");
		runtime.fireEvent({"type": "suspend"});
	};
	window.onResume = function(){
		console.log("[window.onResume]开始执行");
		//CloudAPI.Utility.toast("[window.onResume]开始执行");
		runtime.fireEvent({"type": "resume"});
	};
	window.onLoadData = function(loadData){
		console.log("[onLoadData]" + loadData);
	};
	this._init = function(){
		_super._init.call(this);
		window.CloudAPI = this;  //导出类实例自己[TODO]单例
	};
	this.create = function(name, app){
		_super.create.apply(this, arguments);
	};
	this.dispose = function(){
		_super.dispose.apply(this);
	};
	//判断是否手机环境
	this.isMobile = function(){
		var url = win.location.host;
		return url.indexOf("127.0.0.1") != -1 || /aliyun\.\w{32}\.ch/.test(url);
	};
	if(!this.__debug__){
	//----真实接口----
	this.Telephony  = JsCloudAPI.init(commonPackageName + "Telephony");
	this.Messaging  = JsCloudAPI.init(commonPackageName + "Messaging");
	this.Device     = JsCloudAPI.init(commonPackageName + "Device");
	this.Device.DeviceStateInfo = JsCloudAPI.init(commonPackageName + "DeviceStateInfo");
	this.PIM        = JsCloudAPI.init(commonPackageName + "PIM");
	this.Multimedia = JsCloudAPI.init(commonPackageName + "Multimedia");
	this.Enviroment = JsCloudAPI.init(commonPackageName + "Enviroment");
	this.Utility    = JsCloudAPI.init(commonPackageName + "Utility");
	this.File       = JsCloudAPI.init(commonPackageName + "FileUtility");
	this.HitArea    = JsCloudAPI.init(commonPackageName + "HitArea");
	this.AndroidTel = JsCloudAPI.init(androidPackageName + "AndroidTel");
	this.AndroidMsg = JsCloudAPI.init(androidPackageName + "AndroidMsg");
	//this.ContentProvider   = JsCloudAPI.init(androidPackageName + "AndroidContentProvider");
	//this.BroadcastReceiver = JsCloudAPI.init(androidPackageName + "AndroidBroadcastReceiver");
	this.Alipay     = JsCloudAPI.init(personalPackageName + "Alipay");
	//this.Intent     = JsCloudAPI.init(androidPackageName + "AndroidIntent");
	//this.Search     = JsCloudAPI.init(personalPackageName + "Search");
	}else{
	//----模拟接口(插桩程序)----
	this.Telephony = {
		sendCall: function(phoneNum){
			stub("拨打电话\nphoneNum=" + phoneNum);
		}
	};
	this.Messaging = {
		sendSms: function(phoneNum, msg){
			stub("发送短信\nphoneNum=" + phoneNum + "\nmsg=" + msg);
		}
	};
	this.Device = {
		launchApplication: function(uuid, loadData){
			stub("启动CloudApp\nuuid=" + uuid + "\nloadData=" + loadData);
			var app = runtime.getActiveApp();
			app.netInvoke("GET", "http://" + uuid, {}, "xml", this, function(xmldoc){
				var url = xmldoc.querySelector("launchurl").getAttribute("value");
				window.open(app._path + url, "_blank");
				win["onLoadData"](loadData);
			});
		},
		debugMode:function(callback){
		},
		scanBarCode: function(onSuccess, onFailure){
			stub("扫描条形码\nonSuccess=" + onSuccess);
			win[onSuccess]("111111");
			//window[onFailure]("error");
		},
		DeviceStateInfo: {
			getCurrentPosition: function(onSuccess, onFailure){
				win[onSuccess]({  //本地开发时的假数据
					"coords": {
						"latitude": "1354856.65",  //纬度
						"longitude": "1354856.65"  //经度
					},
					"address": {
						"city": "杭州"
					}
				});
				//win[onFailure]("调用地理信息接口失败");
			},
			requestLocationInfo: function(onLocationChanged){
				stub("通过GPS或者WIFI获取手机用户所在地\nonLocationChanged" + onLocationChanged);
				win[onLocationChanged]("浙江杭州");
			},
			isNetworkAvailable: function(){
				return win.localStorage && win.localStorage.getItem("offline") == "true" ? "false" : "true";
			},
			wirelessSetting: function(){
				stub("启动无线网络设置界面");
			},
			getNetworkInfo: function(){
				return "wifi";  //wifi方式连接网络
				//return "mobile";  //GPRS、3G等方式连接网路
				//return "false";  //无网络连接
			}
		},
		/**
		 * str格式: {uuid, name, title, icon, x, y, w, h}
		 */
		sendCloudAppInfo: function(str, callback){
			var obj = JSON.parse(str);
			runtime.getWorkspace().showAppBox(obj, obj.x, obj.y, obj.w, obj.h);
			var pane = runtime.getWorkspace().getRootPane();
			if(pane){
				pane.showPaneCap(true, callback);
			}
			//alert(str);
		}
	};
	this.PIM = {
		/*
		getTYToken: function(flag){  //onSuccess
			stub("返回手机用户登录后的淘云token\nflag=" + flag + "[" + (typeof flag) + "]");
			/ *
			win[onSuccess](_token);
			return true;
			* /
			if(flag == "true"){
				stub("启动小云秘注册阿里云帐号");
				//win.alert("启动小云秘注册阿里云帐号");
				return "mock";
			}else{
				return "mock";  //false
			}
		},
		*/
		getTYToken: function(flag, onSuccess, onFailure){  //
			stub("返回手机用户登录后的淘云token\nflag=" + flag + "[" + (typeof flag) + "]");
			var token = "mock";
			if(flag == "true"){
				if(true){
					win[onSuccess](token);
				}else{
					stub("启动小云秘注册阿里云帐号");
					win[onFailure]("获取token失败");
				}
			}else{
				if(true){
					win[onSuccess](token);
				}else{
					win[onFailure]("获取token失败");
				}
			}
		},
		peekTYToken: function(){
			return "mock";  //false
		},
		getSign: function(flag, onSuccess, onFailure){
			stub("[CloudApi::getSign]flag=" + flag + "[" + (typeof flag) + "]");
			//if(flag == "true"){
			if(!CloudAPI.isMobile()){
				//var url = "http://cloudappstore.mobile.aliyun.com/openapi/createsign.php?tyuid=kakapo&tyuidToken=kThiuzKDwx0E6aVNFlp5Z8IAy3reCnmL";
				var url = "http://10.249.195.165/openapi/createsign.php?tyuid=kakapo&tyuidToken=kThiuzKDwx0E6aVNFlp5Z8IAy3reCnmL";
				runtime.getActiveApp().netInvoke("GET", url, "", "json", this, function(json){
					if(json.status == 200){
						_sign = json.data;
						win[onSuccess](_sign);
					}else{
						stub("异步获取sign");
						win[onFailure]("获取sign失败");
					}
				});
			}else{
				if(true){
					win[onSuccess](_sign);
				}else{
					stub("异步获取sign");
					win[onFailure]("获取sign失败");
				}
			}
		},
		peekSign: function(){
			return _sign;
		}
	};
	this.Multimedia = {
		takePhoto: function(type, onSuccess, onFailure){
			stub("拍照并返回图片\nonSuccess=" + onSuccess);
			win[onSuccess](base64);
		},
		pickImage: function(type, onSuccess, onFailure){
			stub("选取图库中的图片并返回地址\nonSuccess=" + onSuccess);
		},
		compressImage: function(imagePath, imageQuality){
			stub("压缩图片\nimagePath=" + imagePath + "\nimageQuality=" + imageQuality);
		}
	};
	this.Utility = {
		log: function(id, msg, type){
		},
		wrapAjaxUrl: function(url){
			return url;
		},
		openBrowser: function(url){
			stub("用浏览器打开一个网址\nurl=" + url);
		},
		openBrower: function(url){
			stub("用浏览器打开一个网址\nurl=" + url);
		},
		toast: function(str){
			stub("[toast]str=" + str);
			runtime.getWorkspace().showTipMsg(str, true);
		},
		/**
		 * @param {String} remoteUrl 下载文件远程地址，例：http://www.example.com/example.jpg
		 * @param {String} fileName  下载后存储到本地的文件名（目前直接存储到/sdcard）
		 * @param {String} onSuccess 下载文件成功后回调的JavaScript函数名
		 * @param {String} onError 下载失败或调用接口发生错误时回调的JavaScript函数名
		 * @param {String} onProgress 下载文件时反馈下载进度回调的JavaScript函数名
		*/
		download: function(remoteUrl, fileName, onSuccess, onError, onProgress){
			win[onSuccess]("/sdcard/aaa.png");
		},
		/**
		 * @param {String} sourceUrl 上传文件在手机上的地址，例：/mnt/sdcard/DCIM/camera/example.jpg
		 * @param {String} remoteUrl 接收上传表单的远程服务器地址
		 * @param {String} fileKey 表单中上传文件字段名，例：file
		 * @param {String} onSuccess 上传文件成功后回调的JavaScript函数名，目前返回服务器端输出
		 * @param {String} onError 上传失败或调用接口发生错误时回调的JavaScript函数名
		 * @param {String} onProgress 上传文件时反馈上传进度回调的JavaScript函数名
		 * @param {Array} options http请求头中添加的键值对数组，例：["key1","value1", "key2","value2", "key3","value3",…]
		 */
		upload: function(sourceUrl, remoteUrl, fileKey, onSuccess, onError, onProgress, options){
		}
	};
	this.File = {
		/**
		 * 将文本内容写入指定文件
		 * @param {String} text 写入文件的文本内容(UTF-8编码)，可以为空字符串，不能为null
		 * @param {String} fileName 创建的文件名(UTF-8编码)，最长64个字符，只能为字母、数字、"."(点)、"-"(连字符)、"_"(下划线) 、空字符串(自动生成文件名)，不能为null
		 * @param {String} override "true"|"false"
		 */
		write: function(text, fileName, override){
			stub("将文本内容写入指定文件\ntext=" + text.substr(0, 100) + "\nfileName=" + fileName);
			return "/sdcard/" + fileName;
		}
	};
	this.Enviroment = {
		/**
		 * 获取下载文件存储路径
		 */
		getDownloadDirectory: function(){
			return "/sdcard";
		}
	};
	this.Android = {
		Telephony: {
			startCall: function(phoneNum){
				stub("调用Android 应用拨打电话\nphoneNum=" + phoneNum);
			}
		},
		Messaging: {
			startSms: function(phoneNum, msg){
				stub("调用Android 应用发送短信\nphoneNum=" + phoneNum + "\nmsg=" + msg);
			}
		}
	};
	this.AndroidTel = {
	};
	this.AndroidMsg = {
	};
	this.Alipay = {
		/**
		 * 调用支付宝底层支付接口支付订单
		 * @param {String} tradeNO 支付宝订单号
		 * @param {String} externToken 淘宝token
		 * @param {String} onSuccess 调用接口成功时回调的javascript函数名，调用接口成功不代表支付成功，需要根据接口返回值判定支付是否成功
		 * @param {String} onError 调用接口失败时回调的javascript函数名
		 */
		pay: function(tradeNO, externToken, onSuccess, onError){
		}
	};
	/*
	this.ContentProvider = {
		query: function(){
			return {
				moveToNext: function(){
					return false;
				},
				close: function(){
				}
			};
		}
	};
	this.BroadcastReceiver = {
		registerReceiver: function(){
		}
	};
	this.Intent = {};
	this.Search ={};
	*/
	}//end if
	//fix runtime cacheserver header options bug
	//PC开发模式下或手机iframe调试模式下，启用代理的方法
	if(this.__debug__ || !this.isMobile()){
		this.wrapProxy = function(url){  //只针对PC开发模式和手机iframe调试模式
			return "/framework/build/proxy.php?u=" + encodeURIComponent(url);
		};
	}else{
		this.wrapProxy = function(url){
			return this.Utility.wrapAjaxUrl(url);
		};
	}
	/**
	 * 日志输出接口
	 * @param {String} id
	 * @param {String} msg 日志消息
	 * @param {String} type 日志类型
	 */
	this.log = function(id, msg, type){
		if(this.__debug__){
			console.log(type, msg);
		}else{
			var xhr;
			var logserver = this.wrapProxy("http://tyid.phpwinder.com/wap.php/app/log");
			if(win.XMLHttpRequest){
				xhr = new XMLHttpRequest();
			}else{
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			}
			xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			xhr.onreadystatechange = function(){
				if(xhr.readyState != 4) return;
				if(xhr.status == 200){
				}
			};
			xhr.open("POST", logserver, true);
			var params = {"id": id, "message": mesg, "type": type};
			var sb = [];
			for(var k in params){
				sb.push(k + "=" + encodeURIComponent(params[k]));
			}
			xhr.send(sb.join("&"));
		}
	};
});